package cn.cxyxj.sso_client_1.controller;

import cn.cxyxj.sso_client_1.utils.JWTUtil;
import cn.cxyxj.sso_client_1.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() throws JsonProcessingException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String s = new ObjectMapper().writeValueAsString(authentication);
        return s;
    }

    /**
     * Oauth2 会重定向到根路径，所以提供接口
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/")
    public String root(HttpServletResponse response) throws JsonProcessingException {
        System.out.println("====================");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        String tokenValue = details.getTokenValue();

        // 将用户的 token 放到 Cookie 中
//        Cookie cookie = new Cookie("sso_client1", tokenValue);
//        response.addCookie(cookie);

        String token = JWTUtil.createToken(principal.toString());

        // 根据用户信息生成局部 token
        RedisUtil.set(String.format("access_token%s",principal),tokenValue);
        RedisUtil.set(String.format("sso_client1%s",principal),token);
        return token;
    }

}